const {
  app,
  BrowserView,
  BrowserWindow,
  Menu,
  ipcMain,
  ipcRenderer,
  Notification,
  screen,
  shell,
  net,
  Tray,
  session,
  dialog
} = require('electron'); //引入electron
const path = require('path');
const fs = require('fs')
var packageInfo = require("./package.json");
const {
  autoUpdater
} = require('electron-updater')

let uploadUrl = 'http://127.0.0.1:8848/update/';
let mainWindow;

let miniWin;

try {
  require('electron-reloader')(module);
} catch (_) { }

let windowConfig = {
  width: 1000,
  height: 720,
  minWidth: 400,
  minHeight: 400,
  frame: false,
  webPreferences: {
    nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了，发现也可以运行
    webSecurity: false,//是否禁用同源策略(上线时删除此配置)
    webviewTag: true
  }
}; //窗口配置程序运行窗口的大小


function createWindow() {
  Menu.setApplicationMenu(null);
  mainWindow = new BrowserWindow(windowConfig); //创建一个窗口
  mainWindow.loadURL(`file://${__dirname}/index.html`); //在窗口内要展示的内容index.html 就是打包生成的index.html
  mainWindow.webContents.openDevTools(); //开启调试工具
  mainWindow.on('close', (e) => {
    //回收BrowserWindow对象
    // let d = new Date();
    // if (d.getHours() > 17) {
    //   e.preventDefault(); //先阻止一下默认行为，不然直接关了，提示框只会闪一下
    //   dialog.showMessageBox({
    //     icon: path.join(__dirname, 'logo.png'),
    //     title: '提示',
    //     message: '关闭前确认，今天发日报了吗？',
    //     buttons: ['确认', '取消'],   //选择按钮，点击确认则下面的idx为0，取消为1
    //     cancelId: 1, //这个的值是如果直接把提示框×掉返回的值，这里设置成和“取消”按钮一样的值，下面的idx也会是1
    //   }).then(idx => {
    //     //注意上面↑是用的then，网上好多是直接把方法做为showMessageBox的第二个参数，我的测试下不成功
    //     if (idx.response == 1) {
    //       e.preventDefault();
    //     } else {
    //       mainWindow = null
    //       app.exit();
    //     }
    //   })
    // }
    mainWindow = null;

  });
  //监听窗口变化
  mainWindow.on('resize', () => {
    if (!mainWindow.isMaximized()) {
      mainWindow.webContents.send('restoreMaximize', 'restore');
    } else {
      mainWindow.webContents.send('restoreMaximize', 'maximize');
    }
  })
  // updateHandle();

}
//解决10.X版本跨域不成功问题(上线删除)
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors');

app.on('ready', () => {
  createWindow()


});

app.on('window-all-closed', () => {
  app.quit();
});

app.on('activate', () => {
  if (mainWindow == null) {
    createWindow();
  }
});


//创建新窗口
ipcMain.on("open-new-window", (e, data) => {
  var window = new BrowserWindow({
    width: 1000,
    height: 720,
    minWidth: 400,
    minHeight: 400,
    webPreferences: {
      nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了，发现也可以运行
      webSecurity: false,//是否禁用同源策略(上线时删除此配置)
      webviewTag: true
    }
  }); //创建一个窗口
  if (data.local) {
    data.url = `file://${__dirname}` + data.url;
  }
  window.loadURL(data.url); //在窗口内要展示的内容index.html 就是打包生成的index.html
  // mainWindow.webContents.openDevTools(); //开启调试工具
  window.on('close', () => {
    //回收BrowserWindow对象
    window = null;
  });
})

//置顶
ipcMain.on('window-top', () => {
  if (mainWindow.isAlwaysOnTop()) {
    mainWindow.setAlwaysOnTop(false);
    mainWindow.webContents.send('alwaysOnTop', 'no');
  } else {
    mainWindow.setAlwaysOnTop(true);
    mainWindow.webContents.send('alwaysOnTop', 'yes');
  }
});

//最小化
ipcMain.on('window-min', () => {
  mainWindow.minimize();
});

ipcMain.on('show-notification', (event, args) => {
  if (Notification.isSupported()) {
    var notification = new Notification({
      title: args.title,
      body: args.body
    })
    notification.show()
  }
});

//最大化
ipcMain.on('window-max', () => {
  if (mainWindow.isMaximized()) {
    mainWindow.restore();
    //主进程 个渲染进程 发送数据
    mainWindow.webContents.send('restoreMaximize', 'restore');
  } else {
    mainWindow.maximize();
    //主进程 个渲染进程 发送数据
    mainWindow.webContents.send('restoreMaximize', 'maximize');
  }
});
ipcMain.on('get-app-info', () => {
  mainWindow.webContents.send('get-app-info-back', packageInfo);
});
//关闭
ipcMain.on('window-close', () => {
  mainWindow.close();
  //setTray()
});

let appTray = null;   // 引用放外部，防止被当垃圾回收
// 隐藏主窗口，并创建托盘，绑定关闭事件
function setTray() {
  // 用一个 Tray 来表示一个图标,这个图标处于正在运行的系统的通知区
  //  ，通常被添加到一个 context menu 上.
  // 系统托盘右键菜单
  let trayMenuTemplate = [{     // 系统托盘图标目录
    label: '退出',
    click: function () {
      app.quit();
    }
  }];
  // 当前目录下的app.ico图标
  let iconPath = path.join(__dirname, 'logo.png');
  appTray = new Tray(iconPath);
  // 图标的上下文菜单
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  // 隐藏主窗口
  mainWindow.hide();
  // 设置托盘悬浮提示
  appTray.setToolTip('never forget');
  // 设置托盘菜单
  appTray.setContextMenu(contextMenu);
  // 单击托盘小图标显示应用
  appTray.on('click', function () {
    // 显示主程序
    mainWindow.show();
    // 关闭托盘显示
    appTray.destroy();
  });

  var notification = new Notification({
    title: 'Awork最小化到任务栏',
    body: '',
    icon: path.join(__dirname, 'logo.png'),
  })
  notification.show()
};

//写出文件
ipcMain.on('create-file', (event, file) => {
  fs.writeFile(file.path + '/' + file.name, file.data, 'utf-8', function (err) {
    if (err) {
      console.log(err);
      return false;
    }
    console.log('写入成功');
  })
});

//写出文件
ipcMain.on('save-file', (event, file) => {
  if (file.saveAs || !file.path || !file.name) {
    dialog.showSaveDialog({
      title: '保存文件',
      defaultPath: file.path + (file.name ? '/' + file.name : ''),
      filters: [
        { name: 'ERM', extensions: ['erm'] }
      ]
    }).then((res) => {
      if (!res.canceled) {
        fs.writeFileSync(res.filePath, file.data)
        mainWindow.webContents.send('save-file-back-' + file.id, res.filePath)
        console.log(res.filePath)
      }
    }).catch((req) => {
      mainWindow.webContents.send('save-file-back-' + file.id, '')
      alert(req)
    })
  } else {
    fs.writeFileSync(file.path + '/' + file.name, file.data)
    //mainWindow.webContents.send('save-file-back-'+file.id, res.filePath)
  }
});



//+++++++++++++++++++++++悬浮工具 start ++++++++++++++++++++++++++++++++++++++
ipcMain.on('main-win-open', () => {
  if (!mainWindow) {
    mainWindow = new BrowserWindow({
      width: 1000,
      height: 720,
      minWidth: 400,
      minHeight: 400,
      frame: false,
      webPreferences: {
        nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了，发现也可以运行
      }
    })
    mainWindow.loadURL(`file://${__dirname}/index.html`); //在窗口内要展示的内容index.html 就是打包生成的index.html
    mainWindow.on('closed', () => {
      mainWindow = null
    })
  } else {
    mainWindow.show();
  }
});

ipcMain.on('open-tool-win', () => {
  const winURL = process.env.NODE_ENV === 'development' ?
    'http://localhost:8080' :
    `file://${__dirname}/index.html`;
  // 定义calendar窗体
  if (!miniWin) {
    var w = screen.getPrimaryDisplay().workAreaSize.width - 700;
    miniWin = new BrowserWindow({
      width: 350,
      maxWidth: 400,
      minWidth: 300,
      height: 200,
      frame: false,
      skipTaskbar: true,
      x: w,
      y: 0,
      transparent: true,
      webPreferences: {
        nodeIntegration: true
      }
    })
    //miniWin.webContents.openDevTools(); //开启调试工具
    miniWin.setAlwaysOnTop(true)
    miniWin.loadURL(winURL + '#/miniTool')
    miniWin.on('closed', () => {
      miniWin = null
    })
    miniWin.on('resized', () => {
      miniWin.webContents.send('mini-resize');
    })
    miniWin.on('blur', (e) => {
      var top = miniWin.getPosition()[1];
      if (top <= 0) {
        miniWin.webContents.send('mini-top', 'true');
      }
    })
    miniWin.on('focus', (e) => {
      var top = miniWin.getPosition()[1];
      if (top <= 0) {
        miniWin.webContents.send('mini-top', 'false');
      }
    })
  }
});

ipcMain.on('mini-win-show', () => {
  miniWin.show();
});

ipcMain.on('mini-win-mouse-leve', () => {
  var top = miniWin.getPosition()[1];
  if (top <= 0) {
    miniWin.webContents.send('mini-top', 'true');
  }
});

ipcMain.on('mini-win-ignore-mouse', () => {
  miniWin.setIgnoreMouseEvents(true, {
    forward: true
  })
});

ipcMain.on('mini-win-close-ignore-mouse', () => {
  miniWin.setIgnoreMouseEvents(false)
});

ipcMain.on('mini-set-size', (event, args) => {
  miniWin.setSize(miniWin.getSize()[0], args, true)
});

ipcMain.on('mini-max-height', (event, args) => {
  miniWin.setSize(miniWin.getSize()[0], screen.getPrimaryDisplay().workAreaSize.height, true)
});

ipcMain.on('mini-close', (event, args) => {
  miniWin.close();
});

ipcMain.on('mini-set-top', (event, args) => {
  miniWin.setAlwaysOnTop(args)
});

//刷新悬浮任务
ipcMain.on('mini-plane-refresh', (event, args) => {
  if (miniWin) {
    miniWin.webContents.send('mini-plane-refresh-call');
  }
});
//刷新任务
ipcMain.on('main-plane-refresh', (event, args) => {
  if (mainWindow) {
    mainWindow.webContents.send('main-plane-refresh-call');
  }
});
//+++++++++++++++++++++++悬浮工具 end ++++++++++++++++++++++++++++++++++++++


//+++++++++++++++++++++++更新 start ++++++++++++++++++++++++++++++

// 检测更新，在你想要检查更新的时候执行，renderer事件触发后的操作自行编写
function updateHandle() {
  let message = {
    error: 'error',
    checking: 'checking',
    updateAva: 'updateAva',
    updateNotAva: 'updateNotAva',
  };
  const os = require('os');

  autoUpdater.setFeedURL(uploadUrl);
  autoUpdater.updateConfigPath = './build/win-unpacked/resources/app-update.yml';

  autoUpdater.on('error', function (error) {
    console.log(error)
    sendUpdateMessage(error)
  });
  autoUpdater.on('checking-for-update', function () {
    sendUpdateMessage(message.checking)
  });
  autoUpdater.on('update-available', function (info) {
    sendUpdateMessage(message.updateAva)
  });
  autoUpdater.on('update-not-available', function (info) {
    sendUpdateMessage(message.updateNotAva)
  });

  // 更新下载进度事件
  autoUpdater.on('download-progress', function (progressObj) {
    console.log(progressObj)
    mainWindow.webContents.send('downloadProgress', progressObj)
  })
  autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {

    ipcMain.on('isUpdateNow', (e, arg) => {
      console.log(arguments);
      console.log("开始更新");
      //some code here to handle event
      autoUpdater.quitAndInstall();
    });

    mainWindow.webContents.send('isUpdateNow')
  });

  autoUpdater.checkForUpdates()
  ipcMain.on("checkForUpdate", () => {
    //执行自动更新检查
    autoUpdater.checkForUpdates();
  })

}

// 通过main进程发送事件给renderer进程，提示更新信息
function sendUpdateMessage(text) {
  mainWindow.webContents.send('message', text)
}

/*
npm install --save babel-core
npm install --save babel-preset-env 或者 npm install --save babel-preset-es2015
npm install babel-cli -g
 */
ipcMain.on("open-url", (e, url) => {
  shell.openExternal(url);
})

ipcMain.on("http-get", (e, data) => {
  const request = net.request(data.url)
  request.on('response', (response) => {
    response.on('data', (chunk) => {
      console.log(`${chunk}`)
      mainWindow.webContents.send('message', {
        type: data.type,
        data: `${chunk}`
      })
    })
    response.on('end', () => { })
  })
  request.end()
})

ipcMain.on("http-post", (e, data) => {
  const request = net.request({
    headers: {
      'Content-Type': 'application/json',
    },
    method: 'POST',
    url: data.url
  })
  request.write(JSON.stringify(data.data))

  request.on('response', (response) => {
    response.on('data', (chunk) => {
      console.log(`${chunk}`)
      mainWindow.webContents.send('message', {
        type: data.type,
        data: `${chunk}`
      })
    })
    response.on('end', () => { })
  })
  request.end()
})


let scanWin = undefined;
ipcMain.on("open-scan-window", (e, url) => {
  const winURL = process.env.NODE_ENV === 'development' ?
    'http://localhost:8080#/scanWorrOperation?url=' + encodeURI(url) :
    `file://${__dirname}/index.html#/scanWorrOperation?url=` + encodeURI(url);


  scanWin = new BrowserWindow({
    width: 800, height: 600,
    icon: path.join(__dirname, 'logo.ico'), webPreferences: {
      nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了，发现也可以运行
      webSecurity: false,//是否禁用同源策略(上线时删除此配置)
      webviewTag: true
    }
  })

  scanWin.webContents.loadURL(winURL)
  // scanWin.webContents.openDevTools(); //开启调试工具

  const xxx_filter = {
    urls: [url + "/*"]
  }
  session.defaultSession.webRequest.onBeforeSendHeaders(xxx_filter, (details, callback) => {
    mainWindow.webContents.send('onBeforeSendHeaders', details);
    callback({ requestHeaders: details.requestHeaders });
  })


  scanWin.on('close', () => {
    scanWin = undefined
  })
})

ipcMain.on("close-scan-window", (e) => {
  if (scanWin) {
    scanWin.close();
  }
})

let scanJmeterWin = undefined;
ipcMain.on("open-scan-jmeter-window", (e, url) => {
  const winURL = process.env.NODE_ENV === 'development' ?
    'http://localhost:8080#/scanJemeterOperation?url=' + encodeURI(url) :
    `file://${__dirname}/index.html#/scanJemeterOperation?url=` + encodeURI(url);


    scanJmeterWin = new BrowserWindow({
    width: 800, height: 600,
    icon: path.join(__dirname, 'logo.ico'), webPreferences: {
      nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了，发现也可以运行
      webSecurity: false,//是否禁用同源策略(上线时删除此配置)
      webviewTag: true
    }
  })

  scanJmeterWin.webContents.loadURL(winURL)
  // scanJmeterWin.webContents.openDevTools(); //开启调试工具

  const xxx_filter = {
    urls: [url + "/*"]
  }
  session.defaultSession.webRequest.onBeforeSendHeaders(xxx_filter, (details, callback) => {
    mainWindow.webContents.send('onBeforeSendHeaders', details);
    callback({ requestHeaders: details.requestHeaders });
  })


  scanJmeterWin.on('close', () => {
    scanJmeterWin = undefined
  })
})

ipcMain.on("open-dev-window", (e) => {
  if (scanWin) {
    scanWin.webContents.openDevTools(); //开启调试工具
  }
})

ipcMain.on("close-scan-jmeter-window", (e) => {
  if (scanJmeterWin) {
    scanJmeterWin.close();
  }
})

ipcMain.on("open-jmeter-dev-window", (e) => {
  if (scanJmeterWin) {
    scanJmeterWin.webContents.openDevTools(); //开启调试工具
  }
})
//刷新 主窗口url
ipcMain.on('scan-main-url-refresh', (event, url) => {
  mainWindow.webContents.send('scan-main-url-refresh-to', url);
});
